package com.leetcode.p0;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 回溯
 */
public class Test93_2 {

    private List<String>  res   = new LinkedList<>();
    private Deque<String> stack = new ArrayDeque<>(4);
    private String        s;
    private int           length;

    public List<String> restoreIpAddresses(String s) {
        this.s = s;
        this.length = s.length();
        if (length < 4 || length > 16) {
            return res;
        }

        dfs(0, 4);

        return res;
    }

    private void dfs(int begin, int reside) {
        if (begin == length) {
            if (reside == 0) {
                res.add(String.join(".", stack));
            }
            return;
        }
        for (int i = begin; i < begin + 3; i++) {
            if (i >= length) {
                break;
            }
            if (length - i > reside * 3) {
                continue;
            }

            if (judgeIpEnable(begin, i)) {
                String curS = s.substring(begin, i + 1);
                stack.addLast(curS);
                dfs(i + 1, reside - 1);
                stack.removeLast();
            }
        }
    }

    private boolean judgeIpEnable(int left, int right) {
        int len = right - left + 1;
        if (len > 1 && s.charAt(left) == '0') {
            return false;
        }
        int res = len <= 0 ? 0 : Integer.parseInt(s.substring(left, right + 1));
        return res >= 0 && res <= 255;
    }

    public static void main(String[] args) {
        Test93_2 test17 = new Test93_2();
        System.out.println(test17.restoreIpAddresses("101023"));
    }

}
